<?php

namespace api\movie;

/**
 * 守兔影票.
 */
class Taototo
{
    private $id;
    private $url;
    private $appkey;
    private $secret;
    private $error;
    private $header = [
        'Content-Type:application/x-www-form-urlencoded',
    ];

    public function __construct($info)
    {
        $this->id = $info['id'];
        $config = json_decode($info['api_config'], true);
        $this->url = rtrim($config['url'], '/');
        $this->appkey = $config['appkey'];
        $this->secret = $config['secret'];
    }

    /**
     * 查询余额.
     *
     * 单位：分
     */
    public function queryAmount()
    {
        $url = $this->url.'/api/user/info';
        $params = $this->getFormatParams([]);

        $res = curlPost($url, http_build_query($params), $this->header);
        // 日志记录
        if (function_exists('doLog')) {
            doLog('守兔影票请求日志，'.$url.'，返回'.$res);
        }
        $res = json_decode($res, true);
        if (!isset($res['data']['balance'])) {
            $this->error = $res['message'] ?? '查询频繁';

            return false;
        }

        // 守兔返回的余额单位是：分
        return $res['data']['balance'];
    }

    /**
     * 请求参数统一处理.
     */
    private function getFormatParams($params = [])
    {
        $params['appKey'] = $this->appkey;
        $params['time'] = time();
        $params['sign'] = $this->getSign($params);

        return $params;
    }

        /**
     * 生成签名.
     */
    private function getSign($params)
    {
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $k.'='.$v.'&';
        }
        $str .= 'appSecret='.$this->secret;

        return md5($str);
    }

    public function getError()
    {
        return $this->error;
    }
}
